/**
 * 添加 script 标签
 * @param {string} url 路径
 * @param {string} id script ID
 */
const addScript = (url, id) => {
  const script = document.createElement('script')
  id && (script.id = id)
  script.src = chrome.runtime.getURL(url)
  document.head.appendChild(script)
}

/**
 * 添加 JS 和事件监听
 */
const addJSAndEventListener = async () => {
  // 监听从页面上下文发回的消息
  window.addEventListener('message', (event) => {
    if (event.data?.type === 'coverage-data') {
      // 从 content 脚本获取到 coverage 数据后，发送给 SW
      chrome.runtime.sendMessage({
        action: 'fromContent2SW-sendCoverage',
        message: {
          ...event.data
        }
      })
    }
  })
  addScript('lucky.js', 'coverage-script')
}

addJSAndEventListener()

chrome.runtime.onMessage.addListener((e, _, sendResponse) => {
  switch (e.action) {
    // 从 SW 发送消息到 content 脚本，获取 coverage 数据
    case 'fromSW2Content-getWindowData': {
      window.postMessage({
        type: 'get-coverage'
      })
      break
    }
    default:
      break
  }
  sendResponse()
  return false
})